﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace TestandoTask
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                var tokenSource = new CancellationTokenSource();
                var token = tokenSource.Token;

                var task1 = new Task(() =>
                                         {
                                             for (int i = 0; i < Int32.MaxValue; i++)
                                             {
                                                 Console.WriteLine("IRÁ CRONOMETRAR.");
                                                 var cancelled = token.WaitHandle.WaitOne(2000);
                                                 Console.WriteLine(
                                                     "....cronometrado.                        Task 1 - Int value {0}. Cancelled? {1}",
                                                     i, cancelled);

                                                 if (cancelled)
                                                     throw new OperationCanceledException(token);
                                             }
                                         }, token);

                task1.Start();

                Console.WriteLine("Press enter to cancel token.");
                Console.ReadLine();

                tokenSource.Cancel();

                Console.WriteLine("Main method complete.   Press enter to finish.");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(" --- CONCLUIDO COM A EXCEPTION {0}. Press enter to finish.", e.Message);
                Console.ReadLine();
            }
            finally
            {
                Console.WriteLine(" --- FINALLY.  Press enter to finish.");
                Console.ReadLine();
            }


        }
    }
}
